package org.dong.samples.service;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dong.samples.dao.ScoreHibernateDAO;
import org.dong.samples.dao.TestHibernateDAO;
import org.dong.samples.dao.UserSubjectHibernateDAO;
import org.dong.samples.model.ExamTest;
import org.dong.samples.model.ExamTestType;
import org.dong.samples.model.Score;
import org.dong.samples.model.Subject;
import org.dong.samples.model.User;
import org.dong.samples.model.vo.ExamTestTypeVO;
import org.dong.samples.model.vo.ExamTestVO;
import org.dong.samples.model.vo.ScoreVO;
import org.dong.samples.model.vo.SubjectVO;
import org.dong.samples.util.NowTime;
import org.dong.samples.util.TestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentService {
	@Autowired
	private ScoreHibernateDAO scoreHibernateDAO;
	
	@Autowired
	private UserSubjectHibernateDAO userSubjectHibernateDAO;
	
	@Autowired
	private TestHibernateDAO testHibernateDAO;
	
	public List<SubjectVO> getSubjectList(User user) throws Exception {
		List<SubjectVO> resultList = new ArrayList<SubjectVO>();
//		List<Subject> subs = userSubjectHibernateDAO.findAllSubject();
		List<Subject> subs2 = userSubjectHibernateDAO.findSubjectByUserId(user.getUserId());
		for(Subject sub:subs2){
			SubjectVO subVO = new SubjectVO();
			BeanUtils.copyProperties(sub, subVO);
			Score score = scoreHibernateDAO.getScore(user.getUserId(), subVO.getSubId());
			if(score !=null){
				ScoreVO scoreVO = new ScoreVO();
				BeanUtils.copyProperties(score, scoreVO);
				//计算考试时间
				Calendar startTime = Calendar.getInstance();
				startTime.setTime(scoreVO.getExamTime());
				Calendar currentTime = Calendar.getInstance();
				currentTime.setTime(new Date());
				long startSecond = startTime.getTimeInMillis();
				long currentSecond = currentTime.getTimeInMillis();
				long totalSecond = sub.getTotalTime()*60;
				scoreVO.setRemainingExamTime(totalSecond - (currentSecond-startSecond)/1000);
				subVO.setScore(scoreVO);
			}
			resultList.add(subVO);
		}
		return resultList;
	}
	
	public ScoreVO getScoreById(Integer scoreId){
		ScoreVO vo = scoreHibernateDAO.getScoreById(scoreId);
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		vo.setExamTimeString(df.format(vo.getExamTime()));
		return vo;
	}
	
	
	public List<ExamTest> getTestListBySubject(Integer subId, String userId) throws Exception {
		List<ExamTest> test = testHibernateDAO.getTestListBySubAndTestType(subId, 1);
		return test;
	}
}
